package qf.api.controller.system;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import qf.api.service.SysUserFeignService;
import qf.common.core.web.vo.AjaxResult;
import qf.common.logback.annotation.Log;
import qf.common.logback.enums.BusinessType;
import qf.common.logback.enums.OperatorType;
import qf.common.security.entitiy.SysUser;
import qf.common.security.utils.JwtUtil;
import qf.common.security.utils.SecurityUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @Title: SysUserContrller
 * @Author itmei
 * @Package qf.api.controller.oauth
 * @Date 2023/3/1 21:18
 * @description: 系统用户权限
 */
@RestController
@RequestMapping("sysuser/api")
public class SysUserContrller {

    @Resource
    private SecurityUtils securityUtils;

    @Resource
    private SysUserFeignService userFeignService;

    @RequestMapping(value = "/v1/oauth",method = RequestMethod.POST)
    @Log(title = "系统授权",businessType = BusinessType.GRANT,operatorType = OperatorType.MANAGE)
    public AjaxResult oAuth(@RequestBody SysUser user) {

        AjaxResult ajaxResult = securityUtils.oAuthSecretKey(user.getBusiNo(), user.getSecretkey());

        if (ajaxResult.isSuccess()) {
            return AjaxResult.success(ajaxResult.getResultData());
        } else {
            return AjaxResult.error(ajaxResult.getResultMsg());
        }
    }

    @RequestMapping(value = "/v1/login",method = RequestMethod.POST)
    @Log(title = "系统授权",businessType = BusinessType.GRANT,operatorType = OperatorType.MANAGE)
    public AjaxResult login(@RequestBody SysUser user) {

        AjaxResult ajaxResult = securityUtils.oAuthPassword(user.getUserName(), user.getPassword());

        if (ajaxResult.isSuccess()) {
            return AjaxResult.success(ajaxResult.getResultData());
        } else {
            return AjaxResult.error(ajaxResult.getResultMsg());
        }
    }

    @RequestMapping(value = "/v1/logout",method = RequestMethod.POST)
    @Log(title = "退出登录",businessType = BusinessType.GRANT,operatorType = OperatorType.MANAGE)
    public AjaxResult logout(){
        return securityUtils.logout();
    }

    @RequestMapping(value = "/v1/save",method = RequestMethod.POST)
    @PreAuthorize("hasAnyAuthority('sysuser:add')")
    @Log(title = "新增用户",businessType = BusinessType.GRANT,operatorType = OperatorType.MANAGE)
    public AjaxResult save(@RequestBody JSONObject sysUser, HttpServletRequest request){
        Long userId = JwtUtil.getAuthorizationUserIdByHeader(request);
        sysUser.put("parentId",userId);
        return userFeignService.save(sysUser);
    }

}
